//
//  AppSettings.m
//  SmartVideo
//
//  Created by nsm on 2019/3/7.
//  Copyright © 2019 nani. All rights reserved.
//

#import "AppSettings.h"
#import <FCUUID.h>

NSString * const kConfiguration     = @"Configuration";
NSString * const kRoute             = @"Route";
NSString * const kChannel           = @"Channel";
NSString * const kVersion           = @"Version";

NSString * const kEnterprise        = @"Enterprise";
NSString * const kPersonal          = @"Personal";

NSString * const kAMapAppkey        = @"AMapAppkey";
NSString * const kJPUSHAppkey       = @"JPUSHAppkey";
NSString * const kUMSocialAppkey    = @"UMSocialAppkey";
NSString * const kWechatAppkey      = @"WechatAppkey";
NSString * const kWechatAppSecret   = @"WechatAppSecret";
NSString * const kQQAppkey          = @"QQAppkey";
NSString * const kQQAppSecret       = @"QQAppSecret";

NSString * const kSalt          = @"4WCqP3LR6Vre^AyN";
NSString * const kRouteDomain   = @"";
NSString * const kBetaDomain    = @"http://pm.test.hbbeisheng.com";
NSString * const kFormalDomain  = @"http://pm.test.hbbeisheng.com";

NSString * const kBetaSocketDomain = @"http://192.168.1.103:5000";
NSString * const kFormalSocketDomain = @"";

#pragma mark - 平台配置
NSDictionary *PrivateData() {
    static NSDictionary *dic;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // !!! 重要数据 放在.plist或.h中容易被破解
        dic = @{kPersonal: @{kQQAppkey: @"",
                             kQQAppSecret: @"",
                             kWechatAppkey: @"",
                             kWechatAppSecret: @"",
                             kUMSocialAppkey: @"5c95c62961f56442f800014f",
                             kJPUSHAppkey: @"",
                             kAMapAppkey: @"ebce732852a16570eabce183bf7e7bc1"},
                kEnterprise: @{kQQAppkey: @"1106921893",
                               kQQAppSecret: @"U8BqKsQMEJgDcM7B",
                               kWechatAppkey: @"wx735487b1af68e1de",
                               kWechatAppSecret: @"a8041c8b30397625947140877b872e5f",
                               kUMSocialAppkey: @"5b333a6a8f4a9d08f6000016",
                               kJPUSHAppkey: @"",
                               kAMapAppkey: @"ebce732852a16570eabce183bf7e7bc1"}};
    });
    return dic;
}

NSDictionary *ConfigurationDictionary() {
    static NSDictionary *dic;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dic = [[[NSBundle mainBundle] infoDictionary] objectForKey:kConfiguration];
    });
    return dic;
}

NSDictionary *PlatformDictionary() {
    BOOL isAppStore = [ConfigurationDictionary()[kChannel] boolValue];
    return PrivateData()[isAppStore?kPersonal:kEnterprise];
}

BOOL IsFormalVersion() {
    return [ConfigurationDictionary()[kVersion] boolValue];
}

NSString *CurrentDomain() {
    return IsFormalVersion()? kFormalDomain: kBetaDomain;
}

NSString *CurrentSocketDomain() {
    return IsFormalVersion()? kFormalSocketDomain: kBetaSocketDomain;
}

NSDictionary *EncodeDictionary(NSDictionary *dict) {
    if (!dict.count) return nil;
    
    // 1.加上时间戳(精确到秒)
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dict];
    mutDic[@"timestamp"] = [NSString stringWithFormat:@"%@", @(time(NULL))];
    // 2.排序从大到小
    NSArray *keys = [mutDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj2 compare:obj1 options:NSLiteralSearch];
    }];
    // 3.加盐
    NSMutableArray *items = [NSMutableArray new];
    for (NSString *key in keys) {
        [items addObject:[NSString stringWithFormat:@"%@=%@", key,mutDic[key]]];
    }
    [items addObject:kSalt];
    // 4.md5
    mutDic[@"sign"] = [[items componentsJoinedByString:@"&"] md5String];
    
    return mutDic;
}

UIImage *PlaceholderImage(void) {
    static UIImage *image;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIImage *icon = [NameImage(@"global_logo") imageByTintColor:COLOR_3];
        CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(icon.CGImage);
        BOOL opaque = (alphaInfo == kCGImageAlphaNoneSkipLast ||
                       alphaInfo == kCGImageAlphaNoneSkipFirst ||
                       alphaInfo == kCGImageAlphaNone);
        CGFloat rate = 2.0;
        CGSize size = CGSizeMake(icon.size.width*rate, icon.size.height*rate);
        UIGraphicsBeginImageContextWithOptions(size, opaque, icon.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, COLOR_5.CGColor);
        CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
        [icon drawAtPoint:CGPointMake((size.width/rate) * ((rate-1)/2.0),
                                      (size.height/rate) * ((rate-1)/2.0))];
        UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        image = imageOut;
    });
    return image;
}

void EndEditing(void) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIApplication.sharedApplication.delegate.window endEditing:YES];
    });
}

@implementation AppSettings
#pragma mark - 全局配置
+ (void)setup {
    [MBProgressHUD appearance].contentColor = COLOR_4;
    [MBRoundProgressView appearance].backgroundTintColor = COLOR_3;
    [MBRoundProgressView appearance].progressTintColor = COLOR_4;
    
    _networker.shouldPrintRequest = ^BOOL{
#if DEBUG
        return YES;
#else
        return NO;
#endif
    };
    _networker.shouldRequestParametersInBody = ^BOOL(NSString *URLString, NSDictionary *parameters) {
        return NO;
    };
    _networker.proxyEnabled = ^BOOL(NSDictionary *parameters) {
        return YES;
    };
    _networker.baseURL = ^NSString *{
        return CurrentDomain();
    };
    _networker.finalURLString = ^NSString *(NSString *URLString) {
        return FormatString(@"%@/api/%@", CurrentDomain(), URLString);
    };
    _networker.finalParameters = ^NSDictionary *(NSDictionary *parameters) {
        return parameters;
        NSMutableDictionary *param = @{}.mutableCopy;
        [param addEntriesFromDictionary:parameters];
        param[@"uid"] = SafeString(_appCache.userInfo.userID);
        param[@"token"] = SafeString(_appCache.userInfo.token);
        param[@"uid"] = @"28";
        param[@"token"] = @"McjxgpO0O0Oh";
        param[@"unique_code"] = [FCUUID uuidForDevice];
        param[@"city_id"] = SafeString(_amapHelper.selectedCity.cid);
        return EncodeDictionary(param);
    };
    _networker.didFailLoad = ^(NSMResponseObject *responseObject, NSError *error) {
        if (error) {
            // 系统级网络错误
            // [[NSMUtilities topViewController] showAlert:error.localizedDescription action:nil];
        } else {
            // 统一处理特殊状态码
            if (responseObject.code == 500) {
                // 用户被禁止
                [_noteCenter postNotificationOnMainThreadWithName:kUserDidDeniedNotification object:nil];
            }
            else if (responseObject.code == 600) {
                // 强制退出app
                UIViewController *vc = UIApplication.sharedApplication.delegate.window.rootViewController;
                [vc showAlert:responseObject.desc action:^(UIAlertAction *action) {
                    exit(0);
                }];
            } else {
                // 过滤一些无需弹框的接口
                NSString *urlStr = responseObject.url;
                BOOL shouldAlert = !([urlStr containsString:@"mine/praise_collect"] ||
                                     [urlStr containsString:@"mine/followUser"] ||
                                     [urlStr containsString:@"publics/version"]);
                // 接口提示出错
                if (shouldAlert) {
                    [[NSMUtilities topViewController] showAlert:responseObject.desc action:nil];
                }
            }
        }
    };
    _networker.willStartLoad = ^(BOOL isShowHud) {
        if (!isShowHud) return;
        UIApplication.sharedApplication.keyWindow.isLoading = YES;
    };
    _networker.didFinishLoad = ^(BOOL isShowHud) {
        if (!isShowHud) return;
        UIApplication.sharedApplication.keyWindow.isLoading = NO;
    };
    
    // 默认值
    _nsmConfig.themeColor = RGBColor(0, 151, 234);
    _nsmConfig.backgroundColor = UIColor.groupTableViewBackgroundColor;
    _nsmConfig.separatorColor = RGBColor(235, 235, 235);
    _nsmConfig.placeholderColor = RGBAColor(0, 0, 25, 0.22);
    _nsmConfig.subtextColor = RGBColor(141, 141, 141);
    
    _nsmConfig.navBarColor = UIColor.redColor;
    _nsmConfig.navTitleColor = COLOR_4;
    _nsmConfig.navItemsColor = COLOR_4;
    _nsmConfig.navItemsDisabledColor = UIColor.lightGrayColor;
    _nsmConfig.navItemsFont = CustomFont(15);
    
    _nsmConfig.tableViewBackgroundColor = UIColor.groupTableViewBackgroundColor;
}

#pragma mark - 便捷方法
+ (void)locationServicesPermission:(void (^)(BOOL, BOOL))handler {
    BOOL servicesEnabled = CLLocationManager.locationServicesEnabled;
    CLAuthorizationStatus status = CLLocationManager.authorizationStatus;
    BOOL enabled = (servicesEnabled &&
                    (status!=kCLAuthorizationStatusRestricted) &&
                    (status!=kCLAuthorizationStatusDenied));
    BOOL notDetermined = (status == kCLAuthorizationStatusNotDetermined);
    !handler?:handler(enabled, notDetermined);
}

+ (void)navigateOnViewController:(UIViewController *)viewController destination:(CLLocationCoordinate2D)coordinate destinationName:(NSString *)name {
    if (!viewController ||
        (coordinate.latitude ==0 && coordinate.longitude==0)) return;
    
    // 检测手机安装了哪些导航应用
    NSMutableArray *titles = @[InternationalString(@"苹果地图")].mutableCopy;
    if (CanOpenURL(@"baidumap://")) [titles addObject:InternationalString(@"百度地图")];
    if (CanOpenURL(@"iosamap://")) [titles addObject:InternationalString(@"高德地图")];
    if (CanOpenURL(@"comgooglemaps://")) [titles addObject:InternationalString(@"谷歌地图")];
    if (CanOpenURL(@"waze://")) [titles addObject:InternationalString(@"Waze")];
    
    if (!titles.count) {
        [viewController showAlert:InternationalString(@"请保证至少安装有一个地图类app: 苹果地图/百度地图／高德地图／谷歌地图/Waze") action:nil];
        return;
    }
    
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil
                                                                         message:nil
                                                                  preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSString *title in titles) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:title style:0 handler:^(UIAlertAction *action) {
            CLLocationCoordinate2D loc = coordinate;
            NSString *urlSting;
            if ([title isEqualToString:InternationalString(@"苹果地图")]) {
                MKMapItem *from = [MKMapItem mapItemForCurrentLocation];
                MKMapItem *to = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:loc addressDictionary:nil]];
                to.name = name;
                [MKMapItem openMapsWithItems:@[from, to]
                               launchOptions:@{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
                                               MKLaunchOptionsShowsTrafficKey: @(YES)}];
            } else if ([title isEqualToString:InternationalString(@"百度地图")]) {
                urlSting = FormatString(@"baidumap://map/direction?origin={{%@}}&destination=latlng:%f,%f|name=%@&mode=driving&coord_type=gcj02",
                                        InternationalString(@"我的位置"),
                                        loc.latitude,
                                        loc.longitude, name);
                OpenURL([urlSting stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]);
            } else if ([title isEqualToString:InternationalString(@"高德地图")]) {
                urlSting = FormatString(@"iosamap://navi?sourceApplication= &backScheme=&lat=%f&lon=%f&dev=0&style=2",
                                        loc.latitude,
                                        loc.longitude);
                OpenURL([urlSting stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]);
            } else if ([title isEqualToString:InternationalString(@"谷歌地图")]) {
                urlSting = FormatString(@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",
                                        kAppBundleName,
                                        @"belt://",
                                        loc.latitude,
                                        loc.longitude);
                OpenURL([urlSting stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]);
            } else if ([title isEqualToString:InternationalString(@"Waze")]) {
                // http://itunes.apple.com/us/app/id323229106 (Waze安装地址)
                urlSting = FormatString(@"https://waze.com/ul?ll=%f,%f&navigate=yes",
                                        loc.latitude,
                                        loc.longitude);
                OpenURL([urlSting stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]);
            }
        }];
        [actionSheet addAction:action];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:InternationalString(@"取消") style:UIAlertActionStyleCancel handler:nil];
    [actionSheet addAction:cancelAction];
    [viewController presentViewController:actionSheet animated:YES completion:nil];
}

+ (UIImage *)getLaunchImage{
    CGSize viewSize = [UIScreen mainScreen].bounds.size;
    NSString *viewOr = @"Portrait";
    NSString *launchImage = nil;
    NSArray *launchImages =  [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    
    for (NSDictionary *dict in launchImages) {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if (CGSizeEqualToSize(viewSize, imageSize) && [viewOr isEqualToString:dict[@"UILaunchImageOrientation"]]) {
            launchImage = dict[@"UILaunchImageName"];
        }
    }
    return [UIImage imageNamed:launchImage];
}

+ (UIImage *)appIcon{
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
    UIImage* image = [UIImage imageNamed:icon];
    return image;
}

@end
